package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.specificationOption.TbSpecificationOption;
import com.dongdongshop.service.specificationOption.SpecificationOptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("specificationOption")
public class SpecificationOptionController {

    @Reference
    private SpecificationOptionService specificationOptionService;

    Logger log = LoggerFactory.getLogger(SpecificationOptionController.class);


    @RequestMapping("getspecificationOptionsBySpecificationId")
    @ResponseBody
    public DataResult getspecificationOptionsBySpecificationId(String specIds){
        List<Map<String,Object>> specificationItems = null;
        try {
            List<Map<String,Object>> list = (List<Map<String,Object>>)JSON.parse(specIds);
            specificationItems = new ArrayList<>();
            for (Map<String, Object> spec : list) {
                Integer idInt = (Integer)spec.get("id");
                Long id = idInt.longValue();
                //查询该规格对应的规格选项
                List<TbSpecificationOption> sos = specificationOptionService.getspecificationOptionsBySpecificationId(id);
                //每个规格和他对应的规格选项集合
                Map<String,Object> map = new HashMap<>();
                //该规格的规格选项集合
                List<String> soList = new ArrayList<>();
                for (TbSpecificationOption so : sos) {
                    soList.add(so.getOptionName());
                }
                map.put("attributeValue",soList);
                map.put("attributeName",spec.get("text"));
                specificationItems.add(map);
            }

        }catch (Exception e){
            log.error("根据规格id查询对应的规格选项异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),specificationItems);
    }
}
